package com.orange.util;


import org.apache.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Created by pengfei on 16/6/11.
 */
public class ActionTemplate {
    private static Logger logger = Logger.getLogger("apiTimeCostLogger");
    public static  BizResponse execute(ActionCallback callback){
        BizResponse res =new BizResponse();
        long t1 = System.currentTimeMillis();
        try{
            callback.callBack(res.getPayload());
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof BizException){
                res.setMsg(((BizException) e).getMsg());
                res.setResultCode(((BizException) e).getCode());
            }else if(e instanceof DuplicateKeyException &&
                    e.getMessage()!=null
                    && e.getMessage().contains("Duplicate entry")
                    && e.getMessage().contains("email")){
                res.setResultCode(2);
                res.setMsg("email已经存在");
            }else{
                res.setResultCode(-1);
                res.setMsg("服务端异常");
            }
        }
        StringBuilder invokeInfo = new StringBuilder();
        try{
            StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
            for(StackTraceElement ele:stacks){
               if(ele.getClassName().contains("FrontAction")){
                   invokeInfo.append(ele.getClassName()+"."+ele.getMethodName());
                   break;
               }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        long t2 = System.currentTimeMillis();
        logger.info(invokeInfo+",消耗:"+(t2-t1)+" ms");
        return res;
    }

}
